/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.httprequest.behaviour;

import org.utc.ia04.antsontheweb.httprequest.agent.HttpReqPoolManager;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

public class PoolManager extends CyclicBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = 7369311259853986549L;

	public void action()
	{
		ACLMessage m = myAgent.receive();
		if(m!=null)
		{
			Requete r;
			try
			{
				r = Requete.deserialize_withException(m.getContent(), myAgent, m);
				if(r.getType() == Requete.REQUESTER_DIE)
					//On supprime un requester
					((HttpReqPoolManager)myAgent).removeRequester(m.getSender());
				else
				{
					//Forward
					m.clearAllReceiver();
					m.addReceiver(selectReceiver());
					myAgent.send(m);
				}
			}
			catch (RequeteException e) { }
		}
		else
			block();
	}
	
	private AID selectReceiver()
	{
		int nbAgent = ((HttpReqPoolManager)myAgent).pool.size();
		int selection = (int) (Math.random()*nbAgent);
		return ((HttpReqPoolManager)myAgent).pool.get(selection);
	}
}
